<?php

//function cache_read($name, $dir = '', $time = 0, $usecache = 1, $default_dir = 'cache') {
//	!empty($dir) or $dir .= '/';
//	empty($default_dir) or $default_dir .= '/';
//	$cachefile = DIR_ROOT .'/'. $default_dir . $dir . $name . '.php';
//	$readcache = $time > 0 && TIME - filemtime($cachefile) > $time ? 0 : 1;
//	$usecache or $readcache = 0;
//	if ($readcache && file_exists($cachefile)) {
//		$data = file_get_contents($cachefile);
//		$data && $data = unserialize($data);
//	} else $data = false;
//	return $data;
//}
//function cache_write($name, $data, $dir = '', $default_dir = 'cache') {
//	empty($dir) or $dir .= '/';
//	empty($default_dir) or $default_dir .= '/';
//	$cachefile = DIR_ROOT .'/'. $default_dir . $dir . $name . '.php';
//	makedir(dirname($cachefile));
//	$data && $data = serialize($data);
//	$strlen = file_put_contents($cachefile, $data);
//	@chmod($cachefile, 0777);
//	return $strlen;
//}
//function cache_delete($name, $dir = '', $default_dir = 'cache') {
//	empty($dir) or $dir .= '/';
//	empty($default_dir) or $default_dir .= '/';
//	$cachefile = DIR_ROOT . $default_dir . $dir . $name . '.php';
//	return @unlink($cachefile);
//}

// Get file content
function read_file($file_name)
{
	if (function_exists('file_get_contents'))
	{
		return @file_get_contents($file_name);
	}

	else
	{
		if (!@$fp = fopen($file_name, 'rb'))
		{
			return false;
		}

		flock($fp, LOCK_SH);
		$content = @fread($fp, filesize($file_name));
		fclose($fp);

		return $content;
	}
}


// Write content to file
function write_file($file_name, $content = '')
{
	if (function_exists('file_put_contents'))
	{
		return @file_put_contents($file_name, $content);
	}

	else
	{
		if (!@$fp = fopen($file_name, 'wb'))
		{
			return false;
		}

		flock($fp, LOCK_UN);
		@fwrite($fp, $content);
		fclose($fp);

		return true;
	}
}


// Append content to file
function append_file($file_name, $content = '')
{
	if (!file_exists($file_name)) {
		@touch($file_name);
	}
	if (!@$fp = fopen($file_name, 'ab'))
	{
		return false;
	}

	flock($fp, LOCK_UN);
	@fwrite($fp, $content);
	fclose($fp);

	return true;
}

// Return first n lines
function head_file($file_name, $n = 10, $crlf = "\n")
{
	if (!@$fp = fopen($file_name, 'rb'))
	{
		return FILE_NOT_FOUND;
	}

	flock($fp, LOCK_SH);

	$ret = array();

	for ($i = 0; $i < $n; $i++)
	{
		$ret[] = fgets($fp);
		if (feof($fp))
		{
			break;
		}
	}
	fclose($fp);

	return $ret;
}

// Return last n lines
function tail_file($file_name, $n = 10, $crlf = "\n")
{
	if ($n < 1)
	{
		return array();
	}

	// 4096 is an experince value, that means max length per line.
	$t_size = 4096 * $n;

	if (!@$fp = fopen($file_name, 'rb'))
	{
		return FILE_NOT_FOUND;
	}

	flock($fp, LOCK_SH);
	$ct = 0;
	$rt = 0;
	$ret = array();

	while(1)
	{
		fseek($fp, 0 - $t_size * ($ct + 1), SEEK_END);
		$content = fread($fp, $t_size);

		$lines = explode($crlf, rtrim($content, "\r\n"));

		$c_start = true;

		// We need n+1 lines!!!
		while(1)
		{
			if ($ct > 0 && $crlf != substr($content, 0 - sizeof($crlf)) && $c_start)
			{
				$ret[$n - $rt] = array_pop($lines) . $ret[$n - $rt];
			}

			else
			{
				$ret[$n - $rt - 1] = array_pop($lines);
				$rt ++;
			}

			$c_start = false;

			if (0 == sizeof($lines) || $rt > $n)
			{
				break;
			}
		}

		if ($rt > $n || strlen($content) < $t_size)
		{
			break;
		}
		$ct ++;
	} // While

	// n lines?
	while(--$rt >= $n)
	{
		array_pop($ret);
	}

	$ret = array_reverse($ret);
	fclose($fp);
	return $ret;
}

// Check a directory. Try to make if not exists
function check_dir($dir_name, $mode = 0777)
{
	$dir_name = str_replace('\\', '/', $dir_name);
	//$dir_name = realpath($dir_name);
	$parts = explode('/', trim($dir_name));
	$pre = substr($dir_name, 0, 1);
	$tested = ('/' == $pre) ? '/' : '';
	for($i = 0; $i < count($parts); $i++)
	{
		$curr = $parts[$i];

		if (isset($curr))
		{
			$tested .= $curr . '/';
			if (!is_dir($tested))
			{
				if (!@mkdir($tested, $mode))
				{
					return false;
				}
			}
		}
	}
	return $tested;
}


// Clear/Remove directory
//function clear_dir($dir, $rmdir = false)
function clear_dir($dir)
{
	if (!@$dir_hdl = opendir($dir))
	{
		return false;
	}

	while (false !== ($file_item = readdir($dir_hdl)))
	{
		if ($file_item != '.' && $file_item != '..')
		{
			$folder_content = $dir . '/' . $file_item;
			if (is_file($folder_content))
			{
				@unlink($folder_content);
			}

			else if (is_dir($folder_content))
			{
				//clear_dir($folder_content . '/', $rmdir);
				clear_dir($folder_content . '/');
			}

			else
			{
				// DO NOTHING
			}
		}
	}

//	if ($rmdirs)
//	{
////		@rmdir ($dir);
//		@unlink($dir);
//	}

	return true;
}

//// Clear/Remove directory
//function clear_dir_file($dir)
//{
//	return true;
//}


// Copy a directory
function copy_dir($src, $dest, $sync = false)
{
	// Source must a valid directory
	if (!is_dir($src))
	{
		return DIR_WRONG_TYPE;
	}

	// Source must writable if sync is true
	if ($sync && !is_writable($src))
	{
		return DIR_READ_ONLY;
	}

	// Check target
	check_dir($dest);

	if (!is_writeable($dest))
	{
		return DIR_READ_ONLY;
	}

	if (!@$s_dir_hdl = opendir($src))
	{
		return DIR_NOT_MATCH;
	}

	if ($sync && !@$d_dir_hdl = opendir($dest))
	{
		return DIR_NOT_MATCH;
	}

	while(false !== ($item = readdir($s_dir_hdl)))
	{
		if ('.' ==  $item || '..' == $item)
		{
			continue;
		}

		$file = true_path($src . '/' . $item);
		$target = true_path($dest . '/' . $item);

		if (is_file($file))
		{
			if (!is_file($target))
			{
				@copy($file, $target);
			}

			else
			{
				if ($sync)
				{
					// Keep the newer file!!!
					if (filemtime($target) > filemtime($file))
					{
						@copy($target, $file);
					}

					else
					{
						@copy($file, $target);
					}
				}
			}
		}

		else if (is_dir($file))
		{
			copy_dir($file, $target, $sync);
		}
	}

	// For sync
	if ($sync)
	{
		while(false !== ($item = readdir($d_dir_hdl)))
		{
			if ('.' == $item || '..' == $item)
			{
				continue;
			}

			$file = true_path($dest . '/' . $item);
			$target = true_path($src . '/' . $item);

			if (is_file($file))
			{
				if (!is_file($target))
				{
					@copy($file, $target);
				}
			}

			else if(is_dir($file) && !is_dir($target))
			{
				copy_dir($file, $target, $sync);
			}
		}
	}

	return true;
}

// Download a file from HTTP
function download_file($file_name, $down_name = '', $mt = false)
{
	if (!$down_name)
	{
		$down_name = basename($file_name);
	}

	$filesize = filesize($file_name);

	// Headers
	header("Content-type: application/octet-stream");
	header("Content-type:unknown/unknown;");
	header("Content-Disposition: attachment; filename=\"{$down_name}\"");
	header('Content-transfer-encoding: binary');

	// Multi thread download support.
	// HTTP 206
	if ($mt && $range = getenv('HTTP_RANGE'))
	{
		$range = explode('=', $range);
		$range = $range[1];

		header("HTTP/1.1 206 Partial Content");
		header("Date: " . gmdate("D, d M Y H:i:s") . " GMT");
		header("Server: Apache/2.2.0 (Linux) PHP/5.2.4");
		header("Last-Modified: " . gmdate("D, d M Y H:i:s", filemtime($file_name)) . " GMT");
		header("Accept-Ranges: bytes");
		header("Content-Length:" . ($filesize - $range));
		header("Content-Range: bytes " . $range . ($filesize - 1) . "/" . $filesize);
		header("Connection: close\n\n");
	}
	else
	{
		header("Content-Length:" . $filesize . "\n\n");
		$range = 0;
	}

	if (!@$fp = fopen($file_name, 'wb'))
	{
		echo '';
	}

	fseek($fp, $range);
	// Output 32KB chunk each time.
	while ($buff = fread($fp, 32768))
	{
		echo $buff;
	} // while
	fclose($fp);
	// Exit application!
	exit;
}


// Strip multi slashes
// POSIX only!
//function true_path($str)
//{
//	$ret = trim($str);
//	$ret = preg_replace("/\/+/", '/', $ret);
//	$ret = str_replace('\\','/',$ret);
//	return $ret;
//}

// Return mime type
function true_type_file($file_name)
{
	if (function_exists('mime_content_type'))
	{
		// Mime_Magic supported.
		return mime_content_type($file_name);
	}

	return false;
}

// Return mime type from file extname
function true_type_ext($ext)
{
	$ext = trim($ext, '.');

	switch($ext)
	{
		case '.jpg':
		case '.jpeg':
		default:
			$m = 'plain/text';
	}

	return $m;
}

// Write Cache from an array
function write_array_cache( $arr, $cache_file )
{
	$cache = '';
	// Cache file test
	if ( !touch($cache_file) )
	{
		return false;
	}
	$cache .= "<?php\n";
	$cache .= "/** \r\n";
	$cache .= " * 本文件由 HappyCms ".VERSION." 缓存模块自动生成.\n * 一般情况下，你不要删除它.删除它们可能会引起系统不稳定\n";
	$cache .= " * 当你需要改变这些数据时，你可以使用系统中的缓存更新或者编辑相应选项进行更新. \r\n\r\n";
	$cache .= " * 下面是一些描述\r\n\r\n";
	$cache .= " * 系统名称及版本 : HappyCms Core - " . VERSION . "\n";
	$cache .= " * 产生缓存的时间: " . date('m/d/Y H:i:s') . "\n";
	$cache .= " * 缓存脚本的名称: " . $cache_name . "\r\n";
	$cache .= "*/\r\n\r\n\r\n";
	$cache .= "if(!defined('HAPPY')) exit('Access Denied');\n";
	$cache .= "return array(\n";
	if(is_array($arr)) {
		foreach($arr as $key => $value)
		{
			$cache .= make_arr_code($key, $value);
		}
	}
	$cache .= ");\n\n";
	$cache .= "?>";
	return write_file($cache_file, $cache);
}

// Recover an array into PHP code
function make_arr_code($key, $value)
{
	static $tab_ct = 0;
	$tab_ct ++;
	$content = '';
	if (is_array($value))
	{
		// Still an array
		$content .= str_repeat("\t", $tab_ct) . "'$key' => array(\n";
		foreach($value as $s_key => $s_value)
		{
			$content .= make_arr_code($s_key, $s_value);
		}
		$content .= str_repeat("\t", $tab_ct) . "),\n";
	}
	else
	{
		$content .= (str_repeat("\t", $tab_ct) . "'$key' => ") . ('\'' . $value . '\'');
		$content .= ", \n";
	}

	$tab_ct --;
	return $content;
}


///**
// * 验证文件判断
// *
// * @return bool
// */
//function checkAccredit(){
//	$server_ip = get_server_ip();
//	$server_host = strtolower($_SERVER["SERVER_NAME"]);
//	$accreditFileName = md5($server_ip."zhanguo,runyugame,shanghai,china.".$server_host.GAME_PRIVATE_KEY);
//	$accreditFile = GAME_ROOT . "/{$accreditFileName}.key";
//	if (!file_exists($accreditFile)) {
//		return false;
//	}
//	return true;
//}
?>